<template>
    <div class="trainers-list">
      <div class="header-search">
        <div class="top">
          <div class="left-svg-icons">
            <svg-icon
            icon-class="fastestTime"
            />
            <div class="statistics">
              <div class="fast-title" style="color:#DA7D5D;">最快时间学完</div>
              <div class="name" style="color:#DA7D5D;">{{ fastestUser }}</div>
            </div>
          </div>
          <div class="svg-icons">
            <svg-icon
            icon-class="mostTime"
          />
          <div class="statistics">
            <div class="fast-title" style="color:#18BE86;">观看时间最多</div>
          <div class="name" style="color:#18BE86;">{{ maxDurationUser }}</div>
          </div>
          </div>
          <div class="svg-icons">
            <svg-icon
            icon-class="mostProgress"
          />
          <div class="statistics">
            <div class="fast-title" style="color:#286CBD;">学习进度最多</div>
          <div class="name" style="color:#286CBD;">{{ maxProgressUser }}</div>
          </div>
          </div>
          <div class="svg-icons">
            <svg-icon
            icon-class="everyDay"
          />
          <div class="statistics">
            <div class="fast-title" style="color:#CF8720;">天天观看视频</div>
          <div class="name" style="color:#CF8720;">{{ usersWithDailyWatching }}</div>
          </div>
          </div>
          <div class="right-svg-icons">
            <svg-icon
            icon-class="oneWeek"
          />
          <div class="statistics">
            <div class="fast-title" style="color:#7565B8;">一周未看视频</div>
          <div class="name" style="color:#7565B8;">{{ usersWithoutWatching }}</div>
          </div>
          </div>
        </div>
        <div class="trainers-list-header-search">
          <el-form :inline="true">
            <el-form-item label="姓名：">
              <el-input
                  v-model="searchField.username"
                  placeholder="请输入姓名"
                  clearable
                  class="search-ipt"
                  @clear="handleSearch"
                />
            </el-form-item>
            <el-form-item label="电话：">
              <el-input
                  v-model="searchField.phone"
                  placeholder="请输入电话"
                  clearable
                  @clear="handleSearch"
                />
            </el-form-item>
            <el-form-item label="部门：">
              <el-cascader
                  v-model="currentDepart"
                  :options="departmentOptions"
                  :props="{ checkStrictly: true, multiple: true }"
                  @change="handleCascaderChange"
                  @remove-tag="handleRemoveTag"
                />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearchInfo">重置</el-button>
              <el-button type="primary" @click="addUsersCourse">添加用户</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table
      :header-cell-style="{background:'#F5F7FA ',color:'#333333 '}"
      v-loading="loading"
      :data="trainingList"
      style="width: 100%"
      border
    >
      <el-table-column
        prop="username"
        label="姓名"
        align="center"
      />
      <el-table-column
        prop="gender"
        label="性别"
        align="center"
      >
        <template v-slot="{ row }">
          <div>
            {{ row.gender === 1 ? '男' : row.gender === 0 ? '女' : '不详' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="phone"
        label="联系电话"
        align="center"
      />
        <el-table-column
          prop="username"
          label="部门"
          align="center"
        >
          <template v-slot="{ row }">
            {{ row.userCompany?.department?.name || '-' }}
          </template>
        </el-table-column>
      <el-table-column label="学习进度" align="center">
        <template slot-scope="scope">
          {{ Math.round(scope.row.schedule)*100 }}%
        </template>
      </el-table-column>
      <el-table-column
        prop="latestTime"
        label="最近观看时间"
        align="center"
      />
      <el-table-column label="观看频率" align="center">
        <template slot-scope="scope">
          连续{{ (scope.row.watchedDays) }}天在看
        </template>
      </el-table-column>
      <el-table-column label="观看时长" align="center">
        <template slot-scope="scope">
          {{ Math.round(scope.row.allDuration/3600) }}小时
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="danger" @click="deleteRow(scope.row)" icon="el-icon-delete" circle></el-button>
        </template>
      </el-table-column>
      </el-table>
      <div class="page-ination">
        <Pagination :total="pageInfo.total" :limit="pageInfo.paginate" @pagination="handlePagination" />
      </div>
      <el-dialog :close-on-click-modal="false"
      :visible.sync="showAddPerson"
      title="添加人员"
    >
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-form-item
          prop="user_id"
          label="选择添加人员："
        >
          <el-select
            v-model="formData.user_id"
            filterable
            :filter-method="handleFilterMethods"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handelUserCourse">确定</el-button>
      </span>
    </el-dialog>
    </div>
  </template>
  
  <script>
  import { getDept } from '@/api/basic'
  import Pagination from '@/components/Pagination'
  import { statistics, progress, addUserCourse,deleteUserCourses } from '@/api/train'
  import { getAllUser } from '@/api/personnel'
  export default {
    name: '',
    components: {
      Pagination,
    },
    data() {
      return {
        loading: false,
        trainingList: [],
        course_id:[],
        showAddPerson: false,
        formData: {
          user_id: null,
        },
        rules: {
        user_id: 
          [
            { required: true, message: '请选择添加人员', trigger: ['blur', 'change'] }
          ]
        },
        options: [],
        keywords: '',
        userListID:[],
        pageInfo: {
          paginate: 10,
          total: 0,
          page: 1
        },
        course: [],
        searchField: {
          username: '',
          phone: '',
          department_id: null
        },
        currentDepart: null,
        departmentOptions: [],
        fastestUser: '', // 最快时间完成
        maxDurationUser: '', // 观看时间最多
        maxProgressUser: '', // 学习进度最多
        usersWithDailyWatching: '', // 天天观看视频
        usersWithoutWatching: '', // 一周未看视频
      }
    },
    created() {
      this.init()
      this.statistics()
      this.course_id.push(this.$route.query.id)
    },
    methods: {
      async init() {
        const result = await Promise.allSettled([
          this.getTrainingList(),
          this.getDepartmentList()
        ])
        console.log('result ------>', result)
      },
      async getTrainingList() {
        this.loading = true
        const params = {
          course_id: this.$route.query.id,
          name: this.searchField.username,
          phone: this.searchField.phone,
          department: this.searchField.department_id,
          paginate: this.pageInfo.paginate,
          page: this.pageInfo.page,
        }
        try {
          const res = await progress(params)
          this.trainingList = res.data
          this.pageInfo.total = res.meta.total
          res.data.forEach(item=>{
            this.userListID.push(item.id)
          })
          console.log('res ------>', res)
        } catch (error) {
          console.log('error ------>', error)
        } finally {
          this.loading = false
        }
      },
      async statistics() {
        const params = {
          course_id: this.$route.query.id
        }
        const res = await statistics(params)
        this.maxDurationUser = res.data.maxDurationUser
        this.maxDurationUser = res.data.maxDurationUser
        this.maxProgressUser = res.data.maxProgressUser
        this.usersWithDailyWatching = res.data.usersWithDailyWatching
        this.usersWithoutWatching = res.data.usersWithoutWatching
        console.log(res,111122223333);
      },
      async getDepartmentList() {
        try {
          const res = await getDept()
          this.departmentOptions = this.formatDepartmentsOptions(res.data)
        } catch (error) {
          console.log('error ------>', error)
        }
      },
      formatDepartmentsOptions(depart) {
        return depart.reduce((pre, cur) => {
          if (!cur.children || cur.children.length <= 0) {
            pre.push({ value: cur.id, label: cur.name })
          } else {
            const item = { value: cur.id, label: cur.name, children: [] }
            const child = this.formatDepartmentsOptions(cur.children)
            item.children.push(...child)
            pre.push(item)
          }
          return pre
        }, [])
      },
      handlePagination(e) {
        this.pageInfo.paginate = e.limit
        this.pageInfo.page = e.page
        this.getTrainingList()
        console.log('e ------>', e)
      },
      handleSearch() {
        console.log(this.searchField,6666666666);
        this.pageInfo.page = 1
        this.getTrainingList()
      },
      resetSearchInfo() {
        this.pageInfo = this.$options.data().pageInfo
        this.searchField = this.$options.data().searchField
        this.currentDepart = null
        this.getTrainingList()
      },
      addUsersCourse(){
        this.showAddPerson=true
        this.$nextTick(()=>{
          this.getEmployessList()
        })
      },
      handleFilterMethods(e) {
        console.log('e ------>', e)
        this.keywords = e
        this.getEmployessList()
      },
      async getEmployessList() {
        try {
          const res = await getAllUser({
            username: this.keywords,
            job_status:1,
            type:2
          })
          // res.data.filter(item=>{
          //   this.userListID.forEach(userItem=>{
          //     if (item.id!==userItem) {
          //       return {
          //         label: item.username,
          //         value: item.id
          //       }
          //     }
          //   })
          // })
          this.options = res.data.map(item => {
            return {
              label: item.username,
              value: item.id
            }
          })
        } catch (error) {
          this.$message.error('获取员工信息失败')
          console.log('error ------>', error)
        }
      },
      async handelUserCourse(){
        try {
          await addUserCourse({user_id:JSON.stringify(this.formData.user_id),course_id:JSON.stringify(this.course_id)})
          this.showAddPerson = false
          this.$message.success('添加成功')
          this.init()
          this.statistics()
        } catch (error) {
          console.log(error);
        }
      },
      async deleteUsersCourse(params){
        try {
          await deleteUserCourses(params)
          this.$message.success('删除成功')
          this.init()
          this.statistics()
        } catch (error) {
          console.log(error);
        }
      },
      closeDialog() {
        this.showAddPerson = false
      },
      deleteRow(row){
        this.$confirm(
        '是否删除该字段',
        {
          type: 'warning',
          cancelButtonText: '取消',
          confirmButtonText: '确定'
        }
        ).then(() => {
          const params={
            user_id:row.id,
            course_id:JSON.stringify(this.course_id)
          }
          console.log(params);
          this.deleteUsersCourse(params)
        })
      },
      handleCascaderChange(e) {
        console.log('e ------>', e)
        const list = []
        e.forEach(item => {
          list.push(item[item.length - 1])
        })
        this.searchField.department_id = list.length > 0 ? list : null
      },
      handleRemoveTag(e) {
        console.log('e handleRemoveTag------>', e)
        this.searchField.department_id = this.searchField.department_id.filter(item => item !== e[e.length - 1])
        this.searchField.department_id = this.searchField.department_id.length > 0
          ? this.searchField.department_id : null
        console.log('this.searchField.department_id ------>', this.searchField.department_id)
        this.handleSearch()
      }
    }
  }
  </script>
  
  <style scoped lang='scss'>
  .trainers-list {
    background-color: #fff;
    padding: 20px;
    .top{
      display: flex;
    }

    .trainers-list-header-search{
      padding-top: 20px;
      margin-right: 40px;
    }
    .left-svg-icons{
      width: 100%;
      height: 128px;
      display: flex;
      position: relative;
      margin-right: 15px;
    }
    .statistics{
      position: absolute;
      top: 30%;
      left: 10%;
    }
    .right-svg-icons{
      width: 100%;
      height: 128px;
      display: flex;
      position: relative;
      margin-left: 15px;
    }
    .svg-icons{
      width: 100%;
      height: 128px;
      display: flex;
      position: relative;
      margin: 0 15px;
    }
    .svg-icon{
      width: 100%;
      height: 128px;
      display: flex;
      position: relative;
    }
    .name{
      font-weight: 400;
      font-size: 24px;
      margin-top: 10px;
    }
    .search-box{
      margin: 20px 0;
      width: 100%;
      .search-warp {
        display: flex;
        align-items: center;
        padding: 10px;
        .title {
          margin-right: 10px;
        }
      }
    }
    .course-list-warp {
      min-height: 200px;
      max-height: 300px;
    }
    .courseAvatar{
      width: 60px;
      height: 60px;
    }
    .image-slot{
      width: 60px;
      height: 60px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
      background: #F5F7FA;
      color: #C0C4CC;
    }
  }
  </style>
  